package com.zy.pay.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zy.pay.api.request.ZyPayRequest;
import com.zy.pay.api.response.ZyPayResponse;
import com.zy.pay.api.util.HttpUtil;
import com.zy.pay.api.util.ZyPayUtil;

/**
 * 默认客户端 <br>
 *
 * @author panweiqiang <br>
 * @date 2020/7/7 9:53 <br>
 */
public class ZyPayDefaultClient implements ZyPayClient {

    private static final Logger logger = LoggerFactory.getLogger(ZyPayDefaultClient.class);

    /**聚合支付地址*/
    private String              url;

    /**聚合支付分配的商户编码*/
    private String              cpCode;

    /**聚合支付分配的签名密钥*/
    private String              signKey;

    /**聚合支付分配的应用id*/
    private String              appId;

    public ZyPayDefaultClient(String url, String cpCode, String signKey, String appId) {
        this.url = url;
        this.cpCode = cpCode;
        this.signKey = signKey;
        this.appId = appId;
    }

    @Override
    public <T extends ZyPayResponse> T execute(ZyPayRequest<T> request) {
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(request);
        jsonObject.put("cp_code", cpCode);
        jsonObject.put("app_id", appId);
        String sign = ZyPayUtil.getSign(jsonObject, signKey);
        jsonObject.put("sign", sign);

        try {
            String response = HttpUtil.sendPost(url + request.getApiEnum().getApi(), jsonObject);
            T object = JSON.parseObject(response, request.getResponseClass());
            logger.info("请求地址：{}，请求参数：{}，返回结果：{}", url + request.getApiEnum().getApi(), jsonObject, JSON.toJSONString(object));
            return object;
        } catch (Exception e) {
            logger.error("请求地址：{}，请求参数：{}，请求失败", url + request.getApiEnum().getApi(), jsonObject, e);
            throw new RuntimeException("聚合支付请求失败");
        }
    }
}
